<!-- 
  MIT License

  Copyright (c) 2023 小辉不会飞

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
-->
<!-- advancedMapboxVectorTiles 高级Mapbox矢量切片地图 -->
<template>
  <div class="container">
    <main-header showBack :title="route.query.name"></main-header>
    <div class="main">
      <div id="map" class="map"></div>
    </div>
    <main-footer></main-footer>
  </div>
</template>

<script setup>
// VUE相关
import { onMounted, reactive } from "vue";
import { useRoute } from "vue-router";
// 项目组件
import mainHeader from "@/components/mainHeader.vue";
import mainFooter from "@/components/mainFooter.vue";
// OL相关
import MVT from "ol/format/MVT";
import Map from "ol/Map";
import TileGrid from "ol/tilegrid/TileGrid";
import VectorTileLayer from "ol/layer/VectorTile";
import VectorTileSource from "ol/source/VectorTile";
import View from "ol/View";
import { Fill, Icon, Stroke, Style, Text } from "ol/style";
import { get as getProjection } from "ol/proj";
import "ol/ol.css";

const route = useRoute(); // 路由对象

const ol = reactive({
  map: null,
});

// 此处请自行到mapbox官网申请Access tokens粘贴过来，使用本人的Access tokens随时可能失效导致无法正常展示地图
const key =
  "pk.eyJ1Ijoiemhhb3lhaHVpIiwiYSI6ImNsMDVhMnhnejBuaWEzam55NG54ZXl4cDUifQ.RvN8sYSBPPZyXs6VAH5sog";

onMounted(() => {
  initMap();
});

/**
 * 初始化地图
 */
const initMap = () => {
  // 初始化地图到指定DOM元素
  ol.map = new Map({
    layers: [
      new VectorTileLayer({
        source: new VectorTileSource({
          attributions:
            '© <a href="https://www.mapbox.com/map-feedback/">Mapbox</a> ' +
            '© <a href="https://www.openstreetmap.org/copyright">' +
            "OpenStreetMap contributors</a>",
          format: new MVT(),
          tileGrid: new TileGrid({
            extent: getProjection("EPSG:3857").getExtent(),
            resolutions: getResolutions(),
            tileSize: 512,
          }),
          tileUrlFunction: tileUrlFunction,
        }),
        style: createMapboxStreetsV6Style(Style, Fill, Stroke, Icon, Text), // index.html中引入mapbox-streets-v6-style.js
      }),
    ], // 图层
    target: "map", // 目标DOM元素
    view: new View({
      center: [0, 0],
      minZoom: 1,
      zoom: 2,
    }), // 视图配置
  });
};

/**
 * 获取resolution值
 */
const getResolutions = () => {
  const resolutions = [];
  for (let i = 0; i <= 8; ++i) {
    resolutions.push(156543.03392804097 / Math.pow(2, i * 2));
  }
  return resolutions;
};

/**
 * 获取tileUrl的函数
 */
// Calculation of tile urls for zoom levels 1, 3, 5, 7, 9, 11, 13, 15.
const tileUrlFunction = (tileCoord) => {
  return (
    "https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/" +
    "{z}/{x}/{y}.vector.pbf?access_token=" +
    key
  )
    .replace("{z}", String(tileCoord[0] * 2 - 1))
    .replace("{x}", String(tileCoord[1]))
    .replace("{y}", String(tileCoord[2]))
    .replace(
      "{a-d}",
      "abcd".substr(((tileCoord[1] << tileCoord[0]) + tileCoord[2]) % 4, 1)
    );
};
</script>

<style scoped lang="scss">
#map {
  width: 100%;
  height: 100%;
}
</style>
